/*
 * Copyright © 2021 http://www.hn-szzy.com/ All rights reserved.
 */
package com.xjh.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjh.bo.CategoryBO;
import com.xjh.mapper.CategoryMapper;
import com.xjh.po.CategoryPO;
import com.xjh.service.CategoryService;
import com.xjh.utils.beanutils.BeanCopyUtils;
import com.xjh.utils.datautils.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author： 徐建华
 * @date： 2022/5/18
 * @description：
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryPO> implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryBO> getCategoryList() {
        // 查出全部层级目录
        List<CategoryBO> categorylist = new ArrayList<>();
        List<CategoryPO> categoryPOS = categoryMapper.selectList(null);
        if (!CollectionUtil.isEmpty(categoryPOS)) {
            List<CategoryBO> categoryBOS = BeanCopyUtils.copyList(categoryPOS, CategoryBO.class);


            Long parentId = 0L;
            categorylist = categoryBOS.stream()
                    //得到所有一级菜单
                    .filter(e -> parentId.equals(e.getParentId()))
                    .peek((menu) -> menu.setChildren(getChildren(menu, categoryBOS)))
                    //排序一级菜单
                    .sorted(Comparator.comparingLong(menu ->
                            (Objects.isNull(menu.getSort()) ? 0L : menu.getSort())
                    ))
                    .collect(Collectors.toList());//一级分类的所有数据变成一个list集合
            log.info("排序后" + categorylist);
        }
        return categorylist;//返回所有一级分类
    }


    private List<CategoryBO> getChildren(CategoryBO root, List<CategoryBO> all) {
        List<CategoryBO> children = all.stream().filter(e ->
                        e.getParentId().equals(root.getId()))
                .peek(e -> {
                    e.setChildren(getChildren(e, all));
                })
                //排序二级及以后菜单
                .sorted(Comparator.comparingLong(menu ->
                        (Objects.isNull(menu.getSort()) ? 0L : menu.getSort())
                ))
                .collect(Collectors.toList());
        return children;
    }

    // todo 根据一个id，查出其所有父和子数据，并形成嵌套结构
}
